const gohttp = require('gohttp');
const wxkey = require('./gzhkey');

function fmtTokenApi (appid, secret) {
  return `https://api.weixin.qq.com/cgi-bin/token`
        + `?grant_type=client_credential`
        + `&appid=${appid}&secret=${secret}`
}

async function getToken() {
  let url = fmtTokenApi(wxkey.appid, wxkey.secret)

  let t = await gohttp.get(url)

  if (t.status !== 200) {
    console.error(`Error: status ${c.status}`)
    return false
  }

  let tk = t.json()

  if (tk.access_token === undefined) {
    console.error(JSON.stringify(tk))
    return false
  }

  return tk
}


var menu_data = {
    button : [
      {
        type : "view",
        name : "Node doc",
        url  : "https://nodejs.org/dist/latest-v14.x/docs/api/"
      },
      {
        type : "view",
        name : "MDN-JS",
        url  : "https://developer.mozilla.org/zh-CN/docs/Web/JavaScript"
      },
      {
        name : "更多",
        sub_button : [
          {
            type : "click",
            name : "关于",
            key  : "about"
          },
          {
            type : "click",
            name : "帮助",
            key : "help"
          }
        ]
      }
    ]
};

(async () => {

  let t = await getToken()

  if (t === false) {
    console.error('get access_token failed')
    return false
  }

  var json_menu = JSON.stringify(menu_data);

  var create_menu_api = `https://api.weixin.qq.com/cgi-bin/menu/create`
        +`?access_token=${t.access_token}`;

  let ret = await gohttp.post(create_menu_api, {
    body : json_menu,
    headers : {
      'content-type'  : 'text/plain'
    }
  });
  
  console.log(ret.text());

})();
